﻿YAHOO.example.init = function () {
    function onButtonClick(p_oEvent) {
        switch (this.get("id")) {
            case "btnSave":
                Save(flag);
                break;
            case "btnClose":
                Close();
                break;
            case "btnNew1":
                handleAdd();
                break;
            case "btnDelete1":
                handleDelete();
                break;
            case "btnPay":
                handlePay();
                break;
            case "btnAgree":
                handleAgree();
                break;
            case "btnUnAgree":
                YAHOO.example.container.dialog4.show();
                break;
            case "btnOK":
                handleOK();
            default:
                break;
        }
    }
    YAHOO.util.Event.onContentReady("toolbar", function () {
        btnSave = new YAHOO.widget.Button("btnSave");
        btnSave.on("click", onButtonClick);
        btnClose = new YAHOO.widget.Button("btnClose");
        btnClose.on("click", onButtonClick);
        btnPay = new YAHOO.widget.Button("btnPay");
        btnPay.on("click", onButtonClick);
        btnAgree = new YAHOO.widget.Button("btnAgree");
        btnAgree.on("click", onButtonClick);
        btnUnAgree = new YAHOO.widget.Button("btnUnAgree");
        btnUnAgree.on("click", onButtonClick);
        btnOK = new YAHOO.widget.Button("btnOK");
        btnOK.on("click", onButtonClick);
        if (view == "unDone" && OperStatus == "1") {  //退回原点，允许修改信息
            btnOK._button.style.display = "none";
            $("#btnOK").attr('disabled', "true");
            btnAgree._button.style.display = "none";
            $("#btnAgree").attr('disabled', "true");
            btnUnAgree._button.style.display = "none";
            $("#btnUnAgree").attr('disabled', "true");
            btnPay._button.style.display = "none";
            $("#btnPay").attr('disabled', "true");
            $("#StateID").attr("disabled", "true");
            return;
        }
        if (flag == "1" && view == "") {  //流程
            btnOK._button.style.display = "none";
            $("#btnOK").attr('disabled', "true");
            btnSave._button.style.display = "none";
            $("#btnSave").attr('disabled', "true");
            btnPay._button.style.display = "none";
            $("#btnPay").attr('disabled', "true");
            $("#StateID").attr("disabled", "true");
            return;
        }
        if (view == "check") {
            btnSave._button.style.display = "none";
            $("#btnSave").attr('disabled', "true");
            btnAgree._button.style.display = "none";
            $("#btnAgree").attr('disabled', "true");
            btnUnAgree._button.style.display = "none";
            $("#btnUnAgree").attr('disabled', "true");
            btnPay._button.style.display = "none";
            $("#btnPay").attr('disabled', "true");
            return;
        } else {
            if (flag == "4") {
                btnSave._button.style.display = "none";
                $("#btnSave").attr('disabled', "true");
                btnOK._button.style.display = "none";
                $("#btnOK").attr('disabled', "true");
                btnAgree._button.style.display = "none";
                $("#btnAgree").attr('disabled', "true");
                btnUnAgree._button.style.display = "none";
                $("#btnUnAgree").attr('disabled', "true");
                btnPay._button.style.display = "none";
                $("#btnPay").attr('disabled', "true");
                return;
            } else if (flag == "0") {
                btnOK._button.style.display = "none";
                $("#btnOK").attr('disabled', "true");
                btnAgree._button.style.display = "none";
                $("#btnAgree").attr('disabled', "true");
                btnUnAgree._button.style.display = "none";
                $("#btnUnAgree").attr('disabled', "true");
                btnPay._button.style.display = "none";
                $("#btnPay").attr('disabled', "true");
                return;
            } else {
                btnOK._button.style.display = "none";
                $("#btnOK").attr('disabled', "true");
                btnAgree._button.style.display = "none";
                $("#btnAgree").attr('disabled', "true");
                btnUnAgree._button.style.display = "none";
                $("#btnUnAgree").attr('disabled', "true");
                btnPay._button.style.display = "none";
                $("#btnPay").attr('disabled', "true");
                return;
            }
        }
    });
    YAHOO.util.Event.onContentReady("con_two_1", function () {
        btnNews1 = new YAHOO.widget.Button("btnNew1");
        btnNews1.on("click", onButtonClick);
        btnDeletes1 = new YAHOO.widget.Button("btnDelete1");
        btnDeletes1.on("click", onButtonClick);
        if (view == "unDone" && OperStatus == "1") {  //退回原点，允许修改信息
            return;
        }
        if (flag == "1" || flag == "3" || flag == "4") {
            btnNews1._button.style.display = "none";
            $("#btnNew1").attr('disabled', "true");
            btnDeletes1._button.style.display = "none";
            $("#btnDelete1").attr('disabled', "true");
            return;
        }
    });
} ();
//客户选择对应的方法和ID
var _fn, _id;
function ShowDialog(fn, id, src) {
    _fn = fn;
    _id = id;
    document.getElementById("EditUIWindow1").src = src;
    //SetMaxDWH(YAHOO.example.container.dialog1, 50, 50);
    YAHOO.example.container.dialog1.show();
}
//业绩归属选择对应的方法和ID
var _fn, _id;
function ShowDialog2(fn, id) {
    _fn = fn;
    _id = id;
    YAHOO.example.container.dialog2.show();
}
//人员想选择对应的方法和ID
function ShowDialog3(fn, id) {
    _fn = fn;
    _id = id;
    YAHOO.example.container.dialog3.show();
}

//查看状态设置
function GetCheckState() {
    if (view == "unDone" && OperStatus == "1") {  //退回原点，允许修改信息
        var obj = document.getElementById("fieldForm"); //得到DIV对象
        var e = obj.getElementsByTagName("input"); //得到此DIV里的所有INPUT对象
        var s = obj.getElementsByTagName("select");
        for (var j = 0; j < s.length; j++) {
            if (s[j].id == "ProductPackID") { //退回后产品包不允许修改
                s[j].disabled = true;
            }
        }
    } else {
        $('#btnCustomerCode').css("display", "none");
        $('#btnDeptId').css("display", "none");
        $('#btnCustomerZJ').css("display", "none");
        $('#btnCustomerServer').css("display", "none");
        $('#btnCustomerFZ').css("display", "none");
        $('#btnCustomerQD').css("display", "none");
        $('#btnCustomerFD').css("display", "none");
        $('#btnCustomId').css("display", "none");
        $('#btnCourseLoyoutID').css("display", "none");
        var obj = document.getElementById("fieldForm"); //得到DIV对象
        var e = obj.getElementsByTagName("input"); //得到此DIV里的所有INPUT对象
        var s = obj.getElementsByTagName("select");
        var t = obj.getElementsByTagName("textarea");
        for (var i = 0; i < e.length; i++) {
            $("#" + e[i].id + "").attr("readonly", "readonly");
        }
        for (var j = 0; j < s.length; j++) {
            if (s[j].id != "StateID") {
                s[j].disabled = true;
            } else {
                if (flag == "3") {

                } else {
                    $('#StateID').attr("disabled", "true");
                }
            }
        }
        for (var k = 0; k < t.length; k++) {
            $("#" + t[k].id + "").attr("readonly", "readonly");
        }
    }
}

var _NameList = "", _CustomerMrgList = "", _DialogState = "";
YAHOO.namespace("example.container");
YAHOO.util.Event.onDOMReady(function () {
    var handleSubmit = function () {
        var editwindow = document.getElementById("EditUIWindow1");
        if (editwindow) {
            editwindow.contentWindow.ChooseInfo();
            if (_id == "btnCustomerID") {
                LoadCustomerData();
            }
            if (_id == "btnCourseLoyoutID") {
                LoadCourseLayout($("#CourseLoyoutID").val());
            }
        }
        YAHOO.example.container.dialog1.hide();
    };
    var handleSubmit2 = function () {
        var editwindow = document.getElementById("EditUIWindow2");
        if (editwindow) {
            if (_id = "btnDeptId") {
                editwindow.contentWindow.Save();
            } else {
                editwindow.contentWindow.ChooseInfo();
            }
        }
        YAHOO.example.container.dialog2.hide();
    };
    var handleSubmit3 = function () {
        var editwindow = document.getElementById("EditUIWindow3");
        if (editwindow) {
            editwindow.contentWindow.ChooseInfo();
            $("#txtCustomerZJ").val(_NameList);
            $("#CustomerZJ").val(_CustomerMrgList);
            if (_DialogState == "") {
                YAHOO.example.container.dialog3.hide();
                return;
            }
        }
    }
    var handleSubmit4 = function () {
        handleUnAgree();
    }
    var handleCancel = function () {
        this.cancel();
    };
    var handleSuccess = function (o) {
        var response = o.responseText;
        response = response.split("<!")[0];
        document.getElementById("resp").innerHTML = response;
    };
    var handleFailure = function (o) {
        alert("Submission failed: " + o.status);
    };
    YAHOO.example.container.dialog1 = new YAHOO.widget.Dialog("dialog1",
					            { width: "650px",
					                height: "400px",
					                fixedcenter: true,
					                visible: false,
					                draggable: true,
					                close: true,
                                    modal:true,
					                autofillheight: "body",
					                constraintoviewport: true,
					                buttons: [{ text: "确定", handler: handleSubmit, isDefault: true },
								            { text: "取消", handler: handleCancel}]
					            });
    YAHOO.example.container.dialog2 = new YAHOO.widget.Dialog("dialog2",
					            { width: "250px",
					                height: "360px",
					                fixedcenter: true,
					                visible: false,
					                draggable: true,
					                close: true,
					                modal: true,
					                autofillheight: "body",
					                constraintoviewport: true,
					                buttons: [{ text: "确定", handler: handleSubmit2, isDefault: true },
								            { text: "取消", handler: handleCancel}]
					            });
    YAHOO.example.container.dialog3 = new YAHOO.widget.Dialog("dialog3",
					            { width: "650px",
					                height: "350px",
					                fixedcenter: true,
					                visible: false,
					                draggable: true,
					                close: true,
					                modal: true,
					                autofillheight: "body",
					                constraintoviewport: true,
					                buttons: [{ text: "确定", handler: handleSubmit3, isDefault: true },
								            { text: "取消", handler: handleCancel}]
					            });
    //dialog4退回用
	YAHOO.example.container.dialog4 = new YAHOO.widget.Dialog("dialog4",
					            { width: "400px",
					                height: "200px",
					                fixedcenter: true,
					                visible: false,
					                draggable: true,
					                close: true,
					                autofillheight: "body",
					                constraintoviewport: true,
					                buttons: [{ text: "确定", handler: handleSubmit4, isDefault: true },
								            { text: "取消", handler: handleCancel}]
					            }); 
    YAHOO.example.container.dialog1.callback = { success: handleSuccess, failure: handleFailure };
    YAHOO.example.container.dialog1.render();
    YAHOO.example.container.dialog2.callback = { success: handleSuccess, failure: handleFailure };
    YAHOO.example.container.dialog2.render();
    YAHOO.example.container.dialog3.callback = { success: handleSuccess, failure: handleFailure };
    YAHOO.example.container.dialog3.render();
    YAHOO.example.container.dialog4.callback = { success: handleSuccess, failure: handleFailure };
    YAHOO.example.container.dialog4.render();
    //拖动大小dialog1
    var resize1 = new YAHOO.util.Resize("dialog1", {
        handles: ["br"],
        autoRatio: false,
        minWidth: 450,
        minHeight: 300,
        status: false
    });
    resize1.on("startResize", function (args) {
        if (this.cfg.getProperty("constraintoviewport")) {
            var D = YAHOO.util.Dom;
            var clientRegion = D.getClientRegion();
            var elRegion = D.getRegion(this.element);
            resize1.set("maxWidth", clientRegion.right - elRegion.left - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
            resize1.set("maxHeight", clientRegion.bottom - elRegion.top - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
        } else {
            resize1.set("maxWidth", null);
            resize1.set("maxHeight", null);
        }

    }, YAHOO.example.container.dialog1, true);
    resize1.on("resize", function (args) {
        var panelHeight = args.height;
        this.cfg.setProperty("height", panelHeight + "px");
    }, YAHOO.example.container.dialog1, true);
    //拖动大小dialog2
    var resize2 = new YAHOO.util.Resize("dialog2", {
        handles: ["br"],
        autoRatio: false,
        minWidth: 300,
        minHeight: 250,
        status: false
    });
    resize2.on("startResize", function (args) {
        if (this.cfg.getProperty("constraintoviewport")) {
            var D = YAHOO.util.Dom;

            var clientRegion = D.getClientRegion();
            var elRegion = D.getRegion(this.element);

            resize2.set("maxWidth", clientRegion.right - elRegion.left - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
            resize2.set("maxHeight", clientRegion.bottom - elRegion.top - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
        } else {
            resize2.set("maxWidth", null);
            resize2.set("maxHeight", null);
        }

    }, YAHOO.example.container.dialog1, true);
    resize2.on("resize", function (args) {
        var panelHeight = args.height;
        this.cfg.setProperty("height", panelHeight + "px");
    }, YAHOO.example.container.dialog2, true);
    //拖动大小dialog3
    var resize3 = new YAHOO.util.Resize("dialog3", {
        handles: ["br"],
        autoRatio: false,
        minWidth: 300,
        minHeight: 200,
        status: false
    });
    resize3.on("startResize", function (args) {
        if (this.cfg.getProperty("constraintoviewport")) {
            var D = YAHOO.util.Dom;

            var clientRegion = D.getClientRegion();
            var elRegion = D.getRegion(this.element);

            resize3.set("maxWidth", clientRegion.right - elRegion.left - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
            resize3.set("maxHeight", clientRegion.bottom - elRegion.top - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
        } else {
            resize3.set("maxWidth", null);
            resize3.set("maxHeight", null);
        }

    }, YAHOO.example.container.dialog3, true);
    resize3.on("resize", function (args) {
        var panelHeight = args.height;
        this.cfg.setProperty("height", panelHeight + "px");
    }, YAHOO.example.container.dialog3, true);
});
// 设窗口最大化
var SetMaxDWH = function (dialog, width, height) {
    var w = (Y.util.Dom.getViewportWidth() - width) + "px";
    var h = (Y.util.Dom.getViewportHeight() - height) + "px";
    SetDWH(w, h, dialog);
}
// 设置对话框的大小
var SetDWH = function (width, height, dialog) {
    var elements = YAHOO.util.Dom.getElementsByClassName('bd', 'div')[0];
    var w = [],
            h = [];
    w.push(width);
    h.push(height);
    dialog.configWidth(null, w);
    dialog.configHeight(null, h);
    dialog.render();
    if (elements) {
        dialog.fillHeight(elements);
    }
}

var format1 = function (elCell, oRecord, oColumn, sData) {
    if (action == "insert" || flag == "2") {
        var str1 = [];
        var id = "id" + Math.random();
        str1.push("<option value='00'> </option>");
        if (flag == "1" && view == "" || flag == "3" || view == "check") {
            str1.push("<select id='" + id + "' disabled='disabled' name='Caption' style='width:99%;'>");
        } else {
            str1.push("<select id='" + id + "' onchange='ChangeEvent1(this);' name='Caption' style='width:99%;'>");
        }
        str1.push("<option value='00'> </option>");
        for (var i = 0; i < CrmProduct.length; i++) {
            if (CrmProduct[i].Caption == sData) {
                str1.push("<option value='" + CrmProduct[i].Caption + "' selected>" + CrmProduct[i].Caption + "</option>");
            } else {
                str1.push("<option value='" + CrmProduct[i].Caption + "'>" + CrmProduct[i].Caption + "</option>");
            }
        }
        str1.push("</select>");
        elCell.innerHTML = str1.join("");
    } else {
        if (flag == "1" && view == "" || flag == "3" || view == "check" || flag=="4") {
            if (sData == null || sData == "") {
                elCell.innerHTML = "<input type=\"text\" value=\"\" disabled='disabled' name='Caption' style='width:99%; background: #e7eaf4;'>";
            } else {
                elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='Caption' style='width:99%; background: #e7eaf4;'>";
            }
        }
    }
}
var format2 = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='Code' style='width:95%; background: #e7eaf4;'>";
}
var format3 = function (elCell, oRecord, oColumn, sData) {
    if (sData == null || sData == "") {
        elCell.innerHTML = "<input type=\"text\" value=\"\" disabled='disabled' name='PhraseText' style='width:95%; background: #e7eaf4;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='PhraseText' style='width:95%; background: #e7eaf4;'>";
    }
}
var format4 = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='Money' style='width:95%; background: #e7eaf4;'>";
}
var format5 = function (elCell, oRecord, oColumn, sData) {
    if (flag == "1" && view == "" || flag == "3" || view == "check" || flag == "4") {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='Rebate' style='width:95%;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' name='Rebate' onblur='ChangeEvent1(this);' style='width:95%;'>";
    }
}
var format6 = function (elCell, oRecord, oColumn, sData) {
    if (flag == "1" && view == "" || flag == "3" || view == "check" || flag == "4") {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='Amount' style='width:95%;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' name='Amount' onchange='ChangeEvent1(this);' style='width:95%;'>";
    }
}
var format7 = function (elCell, oRecord, oColumn, sData) {
    if (action == "insert" || flag == "2") {
        var str1 = [];
        var id = "id" + Math.random();
        str1.push("<option value='00'> </option>");
        if (flag == "1" && view == "" || flag == "3" || view == "check" || flag == "4") {
            str1.push("<select id='" + id + "' disabled='disabled' name='UnitId' style='width:98%;'>");
        } else {
            str1.push("<select id='" + id + "' onchange='ChangeEvent1(this);' name='UnitId' style='width:98%;'>");
        }
        str1.push("<option value='00'> </option>");
        for (var i = 0; i < CrmListUnitId.length; i++) {
            if (CrmListUnitId[i].PhraseID == sData) {
                str1.push("<option value='" + CrmListUnitId[i].PhraseID + "' selected>" + CrmListUnitId[i].PhraseText + "</option>");
            } else {
                str1.push("<option value='" + CrmListUnitId[i].PhraseID + "'>" + CrmListUnitId[i].PhraseText + "</option>");
            }
        }
        str1.push("</select>");
        elCell.innerHTML = str1.join("");
    }
}
var format8 = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='RebateMoney' style='width:95%; background: #e7eaf4;'>";
}
var format9 = function (elCell, oRecord, oColumn, sData) {
    if (flag == "1" && view == "" || flag == "3" || view == "check" || flag == "4") {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='AccountReceivable' style='width:95%;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" readonly='readonly' name='AccountReceivable' onchange='ChangeEvent1(this);' style='width:95%;'>";
    }
}
var format10 = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='TypeId' style='width:95%; background: #e7eaf4;'>";
}
var format11 = function (elCell, oRecord, oColumn, sData) {
    if (sData == null || sData == "") {
        elCell.innerHTML = "<input type=\"text\" value=\"\" disabled='disabled' name='UnitType' style='width:95%; background: #e7eaf4;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='UnitType' style='width:95%; background: #e7eaf4;'>";
    }
}
var format12 = function (elCell, oRecord, oColumn, sData) {
    elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='ProductId' style='width:95%; background: #e7eaf4;'>";
}
var format13 = function (elCell, oRecord, oColumn, sData) {
    var str1 = [];
    var id = "id" + Math.random();
    str1.push("<option value='00'> </option>");
    str1.push("<select id='" + id + "' disabled='disabled' onchange='ChangeEvent1(this);' name='StateId' style='width:95%;'>");
    for (var i = 0; i < CrmState.length; i++) {
        if (CrmState[i].PhraseID == sData) {
            str1.push("<option value='" + CrmState[i].PhraseID + "' selected>" + CrmState[i].PhraseText + "</option>");
        } else {
            str1.push("<option value='" + CrmState[i].PhraseID + "'>" + CrmState[i].PhraseText + "</option>");
        }
    }
    str1.push("</select>");
    elCell.innerHTML = str1.join("");
}
var formatResign = function (elCell, oRecord, oColumn, sData) {
    if (sData == "" || sData == null) {
        elCell.innerHTML = "<input type=\"text\" value=\"\" disabled='disabled' name='ProductResignMoney' style='width:95%; background: #e7eaf4;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='ProductResignMoney' style='width:95%; background: #e7eaf4;'>";
    }
}
var formatBeResign = function (elCell, oRecord, oColumn, sData) {
    if (sData == "" || sData == null) {
        elCell.innerHTML = "<input type=\"text\" value=\"\" disabled='disabled' name='BeResignMoney' style='width:95%; background: #e7eaf4;'>";
    } else {
        elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\" disabled='disabled' name='BeResignMoney' style='width:95%; background: #e7eaf4;'>";
    }
}

YAHOO.util.Event.addListener(window, "load", function () {
    BindData();
    hideCol();
});
var BindData = function () {
    YAHOO.example.InlineCellEditing = function () {
        var myColumnDefs1 = [
            { key: "ID", label: "ID", resizeable: true },
            { key: "ProductId", label: "ProductId", resizeable: true, formatter: format12 },
            { key: "TypeId", label: "产品类型", resizeable: true, formatter: format10, width: 80 },
            { key: "Caption", label: "产品名称", resizeable: true, formatter: format1, width: 250 },
            { key: "Code", label: "产品编码", resizeable: true, formatter: format2 },
            { key: "PhraseText", label: "产品类型", resizeable: true, formatter: format3, width: 80 },
            { key: "Money", label: "定价", resizeable: true, formatter: format4,width:80 },
            { key: "UnitId", label: "计量单位", resizeable: true, formatter: format7, width: 50 },
            { key: "UnitType", label: "计量单位", resizeable: true, formatter: format11,width:50 },
            { key: "Amount", label: "数量", resizeable: true, formatter: format6,width:50,
                editor: new YAHOO.widget.TextboxCellEditor({validator:YAHOO.widget.DataTable.validateNumber})},
            { key: "Rebate", label: "折扣率(%)", resizeable: true, formatter: format5,width:50,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })},
            { key: "RebateMoney", label: "折扣金额", resizeable: true, formatter: format8,width:80 },
            { key: "AccountReceivable", label: "应收金额", resizeable: true, formatter: format9,width:80,
                editor: new YAHOO.widget.TextboxCellEditor({ validator: YAHOO.widget.DataTable.validateNumber })},
            { key: "ProductResignMoney", label: "已收金额", resizeable: true,width:80, formatter: formatResign },
            { key: "BeResignMoney", label: "待收金额", resizeable: true,width:80, formatter: formatBeResign },
            { key: "StateId", label: "产品状态", resizeable: true, width: 70, formatter: format13 }
            ];
        myDataSource1 = new YAHOO.util.DataSource([{ ID: "", ProductId: "", Code: "", TypeId: "", UnitType: "", Caption: "",
            Money: "", Rebate: "", Amount: "", UnitId: "", UnitType: "", RebateMoney: "",
            ProductResignMoney: "", BeResignMoney: "", AccountReceivable: "", StateId: ""
        }]);
        myDataSource1.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
        myDataSource1.responseSchema = {
            fields: ["ID", "ProductId", "Code", "TypeId", "PhraseText", "Caption", "Money", "Rebate", "Amount",
                     "UnitId", "UnitType", "RebateMoney", "ProductResignMoney", "BeResignMoney", "AccountReceivable", "StateId"]
        };
        var myDataTable1 = new YAHOO.widget.ScrollingDataTable("con_1",
            myColumnDefs1, myDataSource1, { width: "99.8%", height:"100%", selectionMode: "single" });
        mDataTable1 = myDataTable1;
        var i1 = 1,
            bReverseSorted1 = false;
        var trackReverseSorts1 = function (oArg) {
            bReverseSorted1 = (oArg.dir === YAHOO.widget.DataTable.CLASS_DESC);
        };
        var onCellClick = function (e) {
            var ctrl = event.srcElement || e;
            if (ctrl.nodeName == "DIV") {
                
            }
        }
        var onEventSaveCellEditor = function (oArgs) {
            setValue1(oArgs.editor._oColumn.key, oArgs.newData);
        }
        myDataTable1.subscribe("rowMouseoverEvent", myDataTable1.onEventHighlightRow);
        myDataTable1.subscribe("rowMouseoutEvent", myDataTable1.onEventUnhighlightRow);
        myDataTable1.subscribe("rowClickEvent", myDataTable1.onEventSelectRow);  //mousedown
        myDataTable1.subscribe("cellClickEvent", myDataTable1.onEventShowCellEditor);
        myDataTable1.subscribe("editorSaveEvent", onEventSaveCellEditor);
        myDataTable1.subscribe("cellClickEvent", onCellClick);
        myDataTable1.subscribe("checkboxClickEvent", function (oArgs) {
            var elCheckbox = oArgs.target;
            var oRecord = this.getRecord(elCheckbox);
            oRecord.setData("iSun_Selected", elCheckbox.checked);
        });
        GetFormValue();
        return {
            ds: myDataSource1,
            dt: myDataTable1
        };
    } ();
}
//隐藏/栏位
function hideCol() {
    mDataTable1.hideColumn(parseInt(0)); mDataTable1.refreshView();
    mDataTable1.hideColumn(parseInt(1)); mDataTable1.refreshView();
    mDataTable1.hideColumn(parseInt(2)); mDataTable1.refreshView();
    mDataTable1.hideColumn(parseInt(4)); mDataTable1.refreshView();
    if (action == "insert" || flag=="2") {
        mDataTable1.hideColumn(parseInt(8)); mDataTable1.refreshView();
    } else {
        mDataTable1.hideColumn(parseInt(7)); mDataTable1.refreshView();
    }
    if (action == "insert") {
        mDataTable1.hideColumn(parseInt(13)); mDataTable1.refreshView();
        mDataTable1.hideColumn(parseInt(14)); mDataTable1.refreshView();
    } else {
        mDataTable1.showColumn(parseInt(13)); mDataTable1.refreshView();
        mDataTable1.showColumn(parseInt(14)); mDataTable1.refreshView();
    }
}
//值改变事件
var ChangeEvent1 = function (oArgs) {
    var f = oArgs.name;
    var v = oArgs.value;
    setValue1(f, v);
}
//f=字段名 v=值
var record;
var setValue1 = function (f, v) {
    var recordID = mDataTable1.getSelectedRows()[0];
    if (recordID != null && recordID.length != 1) {
        record = mDataTable1.getRecord(recordID);
        record._oData[f] = v;
        for (var i = 0; i < CrmProduct.length; i++) {
            if (CrmProduct[i].Caption == v) {
                record._oData["TypeId"] = CrmProduct[i].TypeId;
                record._oData["ProductId"] = CrmProduct[i].Productid;
                record._oData["PhraseText"] = CrmProduct[i].PhraseText;
                record._oData["Code"] = CrmProduct[i].Code;
                record._oData["Money"] = CrmProduct[i].Money;
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=TypeId]")[0]).val(CrmProduct[i].TypeId);
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=ProductId]")[0]).val(CrmProduct[i].Productid);
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=PhraseText]")[0]).val(CrmProduct[i].PhraseText);
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=Code]")[0]).val(CrmProduct[i].Code);
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=Money]")[0]).val(CrmProduct[i].Money);
            }
        }
        if (f == "Caption") {
            setTextValue();
        }
        if (f == "Amount") {
            if (isNaN(v)) { // || v == "0"
                alert("数量必须输入数字,且不能为0!");
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=Amount]")[0]).val("");
                record._oData["Amount"] = "";
            }
            $("#TotalRebate").val("");
            setTextValue();
        }
        if (f == "AccountReceivable") {
            if (isNaN(v)) {
                alert("应收金额必须输入数字!");
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=AccountReceivable]")[0]).val("");
                record._oData["AccountReceivable"] = "";
            }
            $("#TotalRebate").val("");
            setTextValueReceivable();
        }
        if (f == "Rebate") {
            if (isNaN(v)) {
                alert("折扣率必须输入数字!");
                $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=Rebate]")[0]).val("");
                record._oData["Rebate"] = "";
            } else {
                if (v > 100) {
                    /*alert("折扣率不能超过100%!");
                    $($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=Rebate]")[0]).val("");
                    record._oData["Rebate"] = "";*/
                }
            }
            $("#TotalRebate").val("");
            setTextValue();
        }
    } else {
        alert("请先选中当前行!");
    }
}
var setTextValue = function () {
    var vM = record._oData["Money"];
    if (vM == "") {
        alert("请选择产品!");
        return;
    } else {
        var vMoney = record._oData["Money"];
        var vAmount = 0;
        var vRebate = 100;
        if (record._oData["Amount"] != null && record._oData["Amount"] != "null" && record._oData["Amount"] != "") {
            vAmount = parseFloat(record._oData["Amount"]);
        } else {
            vAmount = 1;
        }
        if (record._oData["Rebate"] != "") {
            vRebate = record._oData["Rebate"];
        }
        if (vAmount == "0") {
            $($($(".yui-dt-selected")[0]).find("input[name=Rebate]")[0]).val("0");
            record._oData["Rebate"] = "0";
        }
        var vRebateMoney = (vMoney * vAmount) - (vMoney * vAmount * (vRebate / 100));
        var vAccountReceivable = (vMoney * vAmount) - vRebateMoney;
        $($($(".yui-dt-selected")[0]).find("input[name=RebateMoney]")[0]).val(vRebateMoney.toFixed(2));
        //$($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=RebateMoney]")[0]).val(vRebateMoney.toFixed(2));
        record._oData["RebateMoney"] = "" + vRebateMoney.toFixed(2) + "";
        //$($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=AccountReceivable]")[0]).val(vAccountReceivable.toFixed(2));
        $($($(".yui-dt-selected")[0]).find("input[name=AccountReceivable]")[0]).val(vAccountReceivable.toFixed(2));
        record._oData["AccountReceivable"] = "" + vAccountReceivable.toFixed(2) + "";

        var list = mDataTable1.getRecordSet()._records;
        var cValue = 0;
        for (var i = 0; i < list.length; i++) {
            if (list[i]._oData.AccountReceivable != "") {
                var v = parseFloat(list[i]._oData.AccountReceivable);
                cValue += v;
            }
        }
        $('#TotalMoney').val(cValue.toFixed(2));
    }
}
var setTextValueReceivable = function () {
    var vM = record._oData["Money"];
    if (vM == "") {
        alert("请选择产品!");
        return;
    } else {
        var vMoney = record._oData["Money"];
        var vAmount = 0;
        var vRebate = 100;
        if (record._oData["Amount"] != "") {
            vAmount = record._oData["Amount"];
        } else {
            alert("请输入数量!");
            return;
        }
        if (record._oData["Rebate"] != "") {
            vRebate = record._oData["Rebate"];
        }
        if (record._oData["AccountReceivable"] == "" || record._oData["AccountReceivable"] == "0") {
            $($($(".yui-dt-selected")[0]).find("input[name=AccountReceivable]")[0]).val("0");
            //$($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=AccountReceivable]")[0]).val("");
            record._oData["AccountReceivable"] = "0";
            $($($(".yui-dt-selected")[0]).find("input[name=Amount]")[0]).val("0");
            record._oData["Amount"] = "0";
            $($($(".yui-dt-selected")[0]).find("input[name=RebateMoney]")[0]).val("0");
            record._oData["RebateMoney"] = "0";
            $($($(".yui-dt-selected")[0]).find("input[name=Rebate]")[0]).val("0");
            record._oData["Rebate"] = "0";
        } else {
            var AccountReceivable = record._oData["AccountReceivable"];
            vRebate = (AccountReceivable / (vMoney * vAmount)) * 100;
            $($($(".yui-dt-selected")[0]).find("input[name=Rebate]")[0]).val(vRebate.toFixed(2));
            //$($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=Rebate]")[0]).val(vRebate.toFixed(2)); 
            record._oData["Rebate"] = "" + vRebate.toFixed(2) + "";
            var vRebateMoney = (vMoney * vAmount) - (vMoney * vAmount * (vRebate / 100));
            $($($(".yui-dt-selected")[0]).find("input[name=RebateMoney]")[0]).val(vRebateMoney.toFixed(2));
            //$($(event.srcElement.parentNode.parentNode.parentNode).find("input[name=RebateMoney]")[0]).val(vRebateMoney.toFixed(2));           
            record._oData["RebateMoney"] = "" + vRebateMoney.toFixed(2) + "";
        }
        var list = mDataTable1.getRecordSet()._records;
        var cValue = 0;
        for (var i = 0; i < list.length; i++) {
            if (list[i]._oData.AccountReceivable != "") {
                var v = parseFloat(list[i]._oData.AccountReceivable);
                cValue += v;
            }
        }
        $('#TotalMoney').val(cValue.toFixed(2));
    }
}
//设置值1
var GetFormValue = function () {
    for (var i = 0; i < CrmOrderProdcut.length; i++) {
        SetFormValue(CrmOrderProdcut);
    }
}
var SetFormValue = function (obj) {
    var arr = eval(obj);
    myDataSource1.liveData = arr;
    mDataTable1.getDataSource().sendRequest(null, { success: mDataTable1.onDataReturnInitializeTable }, mDataTable1);
}

if (typeof ($) != "undefined") {
    $(document).ready(function () {
        LoadCourseLayout($("#CourseLoyoutID").val());
        $('#CourseLoyoutID').change(function () {
            var vValue = $(this).children('option:selected').val();
            if (vValue != "") {
                LoadCourseLayout(vValue);
            } else {
                $("#OrderDate").val("");
                $("#OrderAddress").val("");
            }
        });
        $('#ProductPackID').change(function () {
            var OrderId = $('#ID').val();
            var vValue = $(this).children('option:selected').val();
            if (vValue != "") {
                LoadPackDetail(vValue);
            } else {
                SetFormValue("");
                $('#TotalMoney').val("");
                handleAdd();
            }
            $('#TotalRebate').val("");
        });
        $('#TypeID').change(function () {
            var vValue = $(this).children('option:selected').val();
            if (vValue != "") {
                if (vValue == "53c8dae4-f3c9-4995-bb6a-560123574b81") {  //选择一推
                    $('#trDisplay1').css("display", "none");
                    $('#trDisplay2').css("display", "none");
                    $('#CustomId').val("00000000-0000-0000-0000-000000000000");
                } else {
                    $('#trDisplay1').css("display", "");
                    $('#trDisplay2').css("display", "");
                    var zjlist = $('#CustomerZJ').val();
                    var qd = $('#CustomerQD').val();
                    var fz = $('#CustomerFZ').val();
                    var id = $('#CustomId').val();
                    if (zjlist == "" || zjlist == "00000000-0000-0000-0000-000000000000") {
                        $('#CustomerZJ').val("00000000-0000-0000-0000-000000000000");
                    }
                    if (qd == "" || qd == "00000000-0000-0000-0000-000000000000") {
                        $('#CustomerQD').val("00000000-0000-0000-0000-000000000000");
                    }
                    if (fz == "" || fz == "00000000-0000-0000-0000-000000000000") {
                        $('#CustomerFZ').val("00000000-0000-0000-0000-000000000000");
                    }
                    if (id == "" || id == "00000000-0000-0000-0000-000000000000") {
                        $('#CustomId').val("00000000-0000-0000-0000-000000000000");
                    }
                }
            } else {
                $('#trDisplay1').css("display", "");
                $('#trDisplay2').css("display", "");
                var zjlist = $('#CustomerZJ').val();
                var qd = $('#CustomerQD').val();
                var fz = $('#CustomerFZ').val();
                var id = $('#CustomId').val();
                if (zjlist == "" || zjlist == "00000000-0000-0000-0000-000000000000") {
                    $('#CustomerZJ').val("00000000-0000-0000-0000-000000000000");
                }
                if (qd == "" || qd == "00000000-0000-0000-0000-000000000000") {
                    $('#CustomerQD').val("00000000-0000-0000-0000-000000000000");
                }
                if (fz == "" || fz == "00000000-0000-0000-0000-000000000000") {
                    $('#CustomerFZ').val("00000000-0000-0000-0000-000000000000");
                }
                if (id == "" || id == "00000000-0000-0000-0000-000000000000") {
                    $('#CustomId').val("00000000-0000-0000-0000-000000000000");
                }
            }
        });
        var typeId = $('#TypeID').children('option:selected').val();
        if (typeId == "53c8dae4-f3c9-4995-bb6a-560123574b81") {  //选择一推
            $('#trDisplay1').css("display", "none");
            $('#trDisplay2').css("display", "none");
            $('#CustomId').val("00000000-0000-0000-0000-000000000000");
        } else {
            $('#trDisplay1').css("display", "");
            $('#trDisplay2').css("display", "");
        }
    })
}
//加载订单期数信息
var LoadCourseLayout = function (objValue) {
    var vCId = "ID='" + objValue + "'";
    YAHOO.util.Connect.asyncRequest('GET', "../../Extend/AjaxData/JSONList.aspx?r=" + Math.random() + "&type=1&entity=CrmProductLayout&customCondition=" + vCId + "", //条件 
        {success: function (res) {
            try {
                var str = res.responseText;
                var arr = [];
                var obj = eval(str);
                $("#OrderDate").val(obj[0].BeginDate + "-" + obj[0].EndDate);
                $("#OrderAddress").val(obj[0].Place);
            }
            catch (e) {
            }
            finally {
            }
        }, failure: function () { }
    });
}
//加载产品包详细信息
var LoadPackDetail = function (objValue) {
    var vCId = "PackID='" + objValue + "'";
    YAHOO.util.Connect.asyncRequest('GET', "../../Extend/AjaxData/JSONList.aspx?r=" + Math.random() + "&type=1&entity=V_CrmPackDetail&customCondition=" + vCId + "", //条件 
        {success: function (res) {
            try {
                var str = res.responseText;
                var obj = eval(str);
                var total = 0;
                for (var i = 0; i < obj.length; i++) {
                    SetFormValue(obj);
                    var v = Number(obj[i].AccountReceivable);
                    total += v;
                }
                $('#TotalMoney').val(total.toFixed(2));
            }
            catch (e) {
            }
            finally {
            }
        }, failure: function () { }
    });
}
//选择客户编码显示客户信息
var LoadCustomerData = function () {
    var vCId = "ID='" + $("#CustomerID").val() + "'";
    YAHOO.util.Connect.asyncRequest('GET', "../../Extend/AjaxData/JSONList.aspx?r=" + Math.random() + "&type=1&entity=V_CrmCustomerInfoSale&customCondition=" + vCId + "", //条件 
        {success: function (res) {
            try {
                var str = res.responseText;
                var arr = [];
                var obj = eval(str);
                $("#txtCustomerIDs").val(obj[0].Code);
                $("#CustomerName").val(obj[0].CustomerName);
                $("#CustomerType").val(obj[0].TypeName);
                $("#PersonId").val(obj[0].PersonName);
                $("#TradeId").val(obj[0].TradeName);
                $("#CreateDate").val(obj[0].CompanyCreateDate);
                $("#CompanyProduct").val(obj[0].CompanyProduct);
                $("#Address").val(obj[0].State + obj[0].Province + obj[0].City + obj[0].Address);
                $("#AddUserName").val(obj[0].AddUserName);
                $("#SaleadName").val(obj[0].SaleadviserName);
            }
            catch (e) {
            }
            finally {
            }
        }, failure: function () { }
    });
}

//新增行
var handleAdd = function () {
    mDataTable1.set("sortedBy", null);
    index = mDataTable1.getRecordSet()._records.length;
    var entity = [{ ID: "", Code: "", TypeId: "", Caption: "", Money: "", Rebate: ""
                    , Amount: "", UnitId: "", RebateMoney: "", AccountReceivable: ""
                    , StateId: ""
    }];
    mDataTable1.addRows(entity, index);
}
//产品删除行
var handleDelete = function () {
    var recordID = mDataTable1.getSelectedRows()[0];
    if (recordID != null && recordID.length != 1) {
        if (mDataTable1.getRecordSet()._records.length == 1) {
            alert("最后一行不能删除!");
            return;
        } else {
            var OrderId = $('#ID').val();
            record = mDataTable1.getRecord(recordID);
            var vid = record.getData("ID");
            if (flag == "0" || vid == "" || vid == "00000000-0000-0000-0000-000000000000") {
                mDataTable1.deleteRow(recordID);
                LoadAccountReceivable();
            } else {
                if (confirm("您确定删除该行吗?")) {
                    var SaveUrl = Url + "?r=" + Math.random() + "&action=delete&entity=CrmOrderProduct&json=&oid=" + OrderId + "&id=" + vid;
                    YAHOO.util.Connect.asyncRequest('POST', SaveUrl, {
                        success: function (res) {
                            try {
                                var str = res.responseText;
                                if (str == "1") {
                                    alert("删除成功!");
                                    mDataTable1.deleteRow(recordID);
                                    LoadAccountReceivable();
                                }
                                else {
                                    alert(str + "\n" + "数据删除失败!");
                                    return;
                                }
                            }
                            catch (e) {
                            }
                            finally {
                            }
                        },
                        failure: function (error) {
                            alert("数据错误：" + error.statusText);
                        }
                    }, null);
                }
            }
        }
    } else {
        alert("请选中一行后删除！");
    }
}
function LoadAccountReceivable() {
    var list = mDataTable1.getRecordSet()._records;
    var cValue = 0;
    for (var i = 0; i < list.length; i++) {
        if (list[i]._oData.AccountReceivable != "") {
            var v = Number(list[i]._oData.AccountReceivable);
            cValue += v;
        }
    }
    $('#TotalMoney').val(cValue);
}
//刷新父窗体数据
function RefreshDataParent() {
    if (parent.NeedRefreshPage != null) {
        if (typeof (parent.NeedRefreshPage.LoadData) == "function") {
            parent.NeedRefreshPage.RefreshData();
        }
    }
}
//总折扣率
function TotalRebateChange(value) {
    if (value != "") {
        var elist = [];
        var list = mDataTable1.getRecordSet()._records;
        var TotalRebate = $("#TotalRebate").val();
        for (var i = 0; i < list.length; i++) {
            if (list[i]._oData.ID == "" || list[i]._oData.ID == null) {
                list[i]._oData.ID = "00000000-0000-0000-0000-000000000000";
            }
            if (list[i]._oData.Code == "" || list[i]._oData.Code == "00" || list[i]._oData.Code == null) {
                alert("第" + (i + 1) + "行 产品名称不能为空!");
                $('#TotalRebate').val("");
                return;
            }
            if (list[i]._oData.UnitId == "" || list[i]._oData.UnitId == "00" || list[i]._oData.UnitId == null) {
                alert("第" + (i + 1) + "行 计量单位不能为空!");
                $('#TotalRebate').val("");
                return;
            }
            if (list[i]._oData.Amount == "" || list[i]._oData.Amount == null) {
                alert("第" + (i + 1) + "行 数量不能为空且不能为0!");
                $('#TotalRebate').val("");
                return;
            }
            if (list[i]._oData.Rebate == "" || list[i]._oData.Rebate == null) {
                //alert("第" + (i + 1) + "行 折扣率不能为空!");
                //return;
                list[i]._oData.Rebate = "100";
            }
            if (list[i]._oData.RebateMoney == "" || list[i]._oData.RebateMoney == null) {
                alert("第" + (i + 1) + "行 折扣金额不能为空!");
                $('#TotalRebate').val("");
                return;
            }
            if (list[i]._oData.AccountReceivable == "" || list[i]._oData.AccountReceivable == null) {
                alert("第" + (i + 1) + "行 应该收金额不能为空!");
                $('#TotalRebate').val("");
                return;
            }
            if (TotalRebate != "") {  //总折扣率
                var Rebate = list[i]._oData.Rebate;
                var Money = list[i]._oData.Money;
                var Amount = list[i]._oData.Amount;
                var vAccount = Money * Amount * (TotalRebate / 100);
                var vRebate = (Money * Amount) - vAccount;
                //数量
                list[i]._oData.Amount = Amount;
                //折扣率
                //var v = (Rebate * TotalRebate / 100);
                list[i]._oData.Rebate = TotalRebate;
                //折扣金额
                list[i]._oData.RebateMoney = vRebate.toFixed(2);
                //应收金额
                list[i]._oData.AccountReceivable = vAccount.toFixed(2);
            }
            elist.push(list[i]._oData);
            elist[i].OrderID = $('#ID').val();
        }
        if (confirm("您确定总折扣率为 " + value + "%")) {
            SetFormValue(elist);
            LoadAccountReceivable();
            return;
        } else {
            $('#TotalRebate').val("");
        }
    }
}
//取值
function setValue() {
    instance[0].ID = $('#ID').val();
    instance[0].Code = $('#Code').val();
    instance[0].CustomerId = $('#CustomerID').val();
    instance[0].DeptId = $('#DeptId').val();
    instance[0].Date = $('#Date').val();
    instance[0].TypeID = $('#TypeID').val();
    instance[0].CourseLoyoutID = $('#CourseLoyoutID').val();
    instance[0].ValutaID = $('#ValutaID').val();
    instance[0].PaymentId = $('#PaymentId').val();
    instance[0].StateID = $('#StateID').val();
    instance[0].ProductPackID = $('#ProductPackID').val();
    instance[0].IsPerformance = $('#IsPerformance').val();
    instance[0].Explain = $('#Explain').val().replace(/(^\s*)|(\s*$)/g, '');
    instance[0].TotalMoney = $('#TotalMoney').val();
    instance[0].TeacherTime = "1900-01-01";
    instance[0].EXP1 = $('#TotalRebate').val();    
    instance[0].WorkFlowId = WorkFlowId;
    instance[0].WorkTaskId = WorkTaskId;
    instance[0].WorkFlowInsId = $("#WorkFlowInsId").val();
    instance[0].WorkTaskInsId = $("#WorkTaskInsId").val();
    instance[0].CheckUser = $("#CustomId").val();
    instance[0].AddTime = $("#Date").val();
    var PartIdvZJ = "B059477C-339E-4A78-A443-0AEBE8E52F79"; //客户总监
    var PartIdCustomerServer = "E04EC79E-C283-4001-BE3B-C326EC70D8FF"; //服务人
    var PartIdCustomerFZ = "0A8B6BA1-449E-4716-BD3D-3D00B4E942EE"; //分总
    var PartIdCustomerFD = "D74244F0-C89C-4CBE-9AEF-FDA27498B33A"; //辅导员
    var PartIdCustomerQD = "E8AF1292-B883-42BE-A251-3B3DB1220A9F"; //签单人
    instance[0].CustomerServer = $("#CustomerServer").val();
    instance[0].CustomerFZ = $("#CustomerFZ").val();
    instance[0].CustomerFD = $("#CustomerFD").val();
    instance[0].CustomerQD = $("#CustomerQD").val();
    if (instance[0].CustomerServer == "") {
        instance[0].CustomerServer = "00000000-0000-0000-0000-000000000000";
    }
    /*if (instance[0].CustomerFZ == "") {
        instance[0].CustomerFZ = "00000000-0000-0000-0000-000000000000";
    }*/
    if (instance[0].CustomerFD == "") {
        instance[0].CustomerFD = "00000000-0000-0000-0000-000000000000";
    }
    /*if (instance[0].CustomerQD == "") {
        instance[0].CustomerQD = "00000000-0000-0000-0000-000000000000";
    }*/
    instance[0].CustomerServerList = "@" + PartIdCustomerServer + "︾" + instance[0].CustomerServer + "︾"
                                     + "@" + PartIdCustomerFZ + "︾" + instance[0].CustomerFZ + "︾"
                                     + "@" + PartIdCustomerFD + "︾" + instance[0].CustomerFD + "︾"
                                     + "@" + PartIdvZJ + "︾" + instance[0].CustomerQD + "︾";
    instance[0].CustomerZjList = $("#CustomerZJ").val();
}
//保存
var Save = function (obj) {
    if (flag == "0" || flag == "2" || view == "unDone") { //0新增  2变更 view=unDone退回后修改信息
        setValue();
        if (instance[0].Code == "" || instance[0].Code == null) {
            alert("订单单号不能为空!");
            $('#Code').focus();
            return;
        }      
        if (instance[0].CustomerId == "" || instance[0].CustomerId == null) {
            alert("客户名称不能为空!");
            $('#CustomerName').focus();
            return;
        }
        if (instance[0].Date == "" || instance[0].Date == null) {
            alert("订单日期不能为空!请填写您实际成交日期!");
            $('#Date').focus();
            return;
        }
        if (instance[0].DeptId == "" || instance[0].DeptId == null) {
            alert("业绩归属不能为空!");
            $('#txtDeptId').focus();
            return;
        }
        if (instance[0].PaymentId == "" || instance[0].PaymentId == null) {
            alert("付款方式不能为空!");
            $('#PaymentId').focus();
            return;
        }
        if (instance[0].StateID == "" || instance[0].StateID == null) {
            alert("订单状态不能为空!");
            $('#StateID').focus();
            return;
        }
        if (instance[0].TypeID == "" || instance[0].TypeID == null) {
            alert("销售渠道不能为空!");
            $('#TypeID').focus();
            return;
        }
        if (instance[0].ValutaID == "" || instance[0].ValutaID == null) {
            instance[0].ValutaID = "00000000-0000-0000-0000-000000000000";
            //alert("币别不能为空!");
            //$('#ValutaID').focus();
            //return;
        }
        if (instance[0].PillID == "" || instance[0].PillID == null) {
            instance[0].PillID = "00000000-0000-0000-0000-000000000000";
            //alert("汇率不能为空!");
            //$('#PillID').focus();
            //return;
        }
        if (instance[0].CourseLoyoutID == "" || instance[0].CourseLoyoutID == null) {
            instance[0].CourseLoyoutID = "00000000-0000-0000-0000-000000000000";
            //alert("订单期数不能为空!");
            //$('#CourseLoyoutID').focus();
            //return;
        }
        if (instance[0].ProductPackID == "" || instance[0].ProductPackID == null) {
            instance[0].ProductPackID = "00000000-0000-0000-0000-000000000000";
            //alert("订单期数不能为空!");
            //$('#CourseLoyoutID').focus();
            //return;
        }
        if (instance[0].TypeID != "53c8dae4-f3c9-4995-bb6a-560123574b81") {  //不是一推
            if (instance[0].CustomerZjList == "00000000-0000-0000-0000-000000000000" || instance[0].CustomerZjList == null || instance[0].CustomerZjList == "") {
                alert("签单人不能为空");
                $('#txtCustomerZJ').focus();
                return;
            }
            if (instance[0].CustomerQD == "" || instance[0].CustomerQD == null || instance[0].CustomerQD == "00000000-0000-0000-0000-000000000000") {
                alert("客户总监不能为空!!");
                $('#txtCustomerQD').focus();
                return;
            }
            if (instance[0].CustomerFZ == "" || instance[0].CustomerFZ == null || instance[0].CustomerFZ == "00000000-0000-0000-0000-000000000000") {
                alert("分总不能为空!");
                $('#txtCustomerFZ').focus();
                return;
            }
            if (instance[0].CheckUser == "" || instance[0].CheckUser == null || instance[0].CheckUser == "00000000-0000-0000-0000-000000000000") {
                alert("核算人员不能为空!")
                $("#txtCustomId").focus();
                return;
            }
        }
        var list = mDataTable1.getRecordSet()._records;
        var elist = [];
        instance[0].ProduectList = "";
        var TotalRebate = $("#TotalRebate").val();
        for (var i = 0; i < list.length; i++) {
            if (list[i]._oData.ID == "" || list[i]._oData.ID == null) {
                list[i]._oData.ID = "00000000-0000-0000-0000-000000000000";
            }
            if (list[i]._oData.Code == "" || list[i]._oData.Code == "00" || list[i]._oData.Code == null) {
                alert("第" + (i + 1) + "行 产品名称不能为空!");
                return;
            }
            if (list[i]._oData.UnitId == "" || list[i]._oData.UnitId == "00" || list[i]._oData.UnitId == null) {
                alert("第" + (i + 1) + "行 计量单位不能为空!");
                return;
            }
            if (list[i]._oData.Amount == "" || list[i]._oData.Amount == null) {
                alert("第" + (i + 1) + "行 数量不能为空且不能为0!");
                return;
            }
            if (list[i]._oData.Rebate == "" || list[i]._oData.Rebate == null) {
                //alert("第" + (i + 1) + "行 折扣率不能为空!");
                //return;
                list[i]._oData.Rebate = "100";
            }
            if (list[i]._oData.RebateMoney == "" || list[i]._oData.RebateMoney == null) {
                alert("第" + (i + 1) + "行 折扣金额不能为空!");
                return;
            }
            if (list[i]._oData.AccountReceivable == "" || list[i]._oData.AccountReceivable == null) {
                alert("第" + (i + 1) + "行 应该收金额不能为空!");
                return;
            }
            elist.push(list[i]._oData);
            elist[i].OrderID = $('#ID').val();
        }
        for (var j = 0; j < elist.length; j++) {
            instance[0].ProduectList += "@" + elist[j].ID + "︾" + elist[j].OrderID + "︾" + elist[j].ProductId + "︾" +
                                            elist[j].Rebate + "︾" + elist[j].Amount + "︾" + elist[j].UnitId + "︾" +
                                            elist[j].RebateMoney + "︾" + elist[j].AccountReceivable + "︾";
        }
        if (instance[0].TotalMoney == "" || instance[0].TotalMoney == null) {
            alert("总金额不能为空!");
            $('#TotalMoney').focus();
            return;
        }
        var json = $.toJSON(instance[0]).replace(/'/g, "[B]");
        $("#jsonDataContent").val(json);
        if (flag == "2" || view == "unDone") {
            if (confirm("您确定修改当前订单信息吗?")) {
                if (view == "unDone") {
                    obj = "2";
                    action = "update";
                }
                trySave(obj);
            }
        } else {
            if (confirm("您确定保存当前订单信息?")) {
                trySave(obj);
            }
        }
    } else if (flag == "3") {  //变更    
        if (confirm("您确定变更当前订单状态吗?")) {
            var vName = $("#StateID").find("option:selected").text();
            var CustomerId = $('#CustomerID').val();
            var OrderId = $('#ID').val();
            var OrderStateId = $("#StateID").val();
            if (CustomerId == "") {
                alert("客户ID为空!保存失败!");
                return;
            }
            if (OrderId == "") {
                alert("订单ID为空!保存失败!");
                return;
            }
            if (vName == "") {
                alert("订单状态不能为空!");
                return;
            }
            if (OrderStateId == "" || OrderStateId == "") {
                alert("订单状态不能为空!");
                return;
            }
            var SaveUrl = Url + "?oid=" + OrderId + "&cid=" + CustomerId + "&sid=" + OrderStateId + "&name=" + encodeURI(vName) + "&action=" + action + "&entity=CrmCustomerOrderField";
            YAHOO.util.Connect.asyncRequest('POST', SaveUrl, {
                success: function (res) {
                    try {
                        var str = res.responseText;
                        if (str == "1") {
                            if (obj == 2) {
                                alert("数据保存成功!跳转到缴款单页面!");
                                var title = "新增缴款单信息";
                                window.parent.$("#tabs").tabs('close', title);
                                parent.addTabs(title, '../Crm/Modules/AddPay.aspx?OrderId=' + $('#ID').val() + '&flag=2&entity=CrmPay&title=' + encodeURI(title) + '');
                            } else {
                                alert("数据保存成功");
                            }
                            RefreshDataParent();
                            Close();
                        }
                        else {
                            alert(str);
                        }
                    }
                    catch (e) {
                    }
                    finally {
                    }
                },
                failure: function (error) {
                    alert("数据错误：" + error.statusText);
                }
            }, null);
        }
    }
}
var trySave = function (obj) {
    var formObject = document.getElementById('form2');
    YAHOO.util.Connect.setForm(formObject);
    if (obj == 0) {
        var cObj = YAHOO.util.Connect.asyncRequest('POST', Url + "?flag=1&cName=" + encodeURI($("#CustomerName").val()) + "&view=" + view + "&action=" + action + "&entity=" + entity, callback);
    } else if (obj == 1) {
        var cObj = YAHOO.util.Connect.asyncRequest('POST', Url + "?flag=1&cName=" + encodeURI($("#CustomerName").val()) + "&view=" + view + "&action=" + action + "&entity=" + entity, callback1);
    } else if (obj == 2) {
        var cObj = YAHOO.util.Connect.asyncRequest('POST', Url + "?flag=1&cName=" + encodeURI($("#CustomerName").val()) + "&view=" + view + "&action=" + action + "&entity=CrmCustomerOrderS", callback);
    } else if (obj == 3) {
        var cObj = YAHOO.util.Connect.asyncRequest('POST', Url + "?flag=1&cName=" + encodeURI($("#CustomerName").val()) + "&view=" + view + "&action=" + action + "&entity=CrmCustomerOrderS", callback1);
    }
}
var responseSuccess = function (res) {
    try {
        var str = res.responseText;
        if (str == "1") {
            if (view == "unDone" && OperStatus == "1") {
                handleAgree();
            } else {
                alert("数据保存成功");
                RefreshDataParent(); //刷新父页面
                Close(); //关闭当前页
            }
        } else if (str == "3") {
            RefreshDataParent(); //刷新父页面
            window.location.href = "../../Crm/BasePages/tooltip.aspx?worktaskInstanceId=" + getTsid;
        } else {
            alert(str);
        }
    } catch (e) {
    }
    finally {
    }
};
var responseSuccess1 = function (res) {
    try {
        var str = res.responseText;
        if (str == "1") {
            alert("数据保存成功!跳转到缴款单页面!");
            var title = "新增缴款单信息";
            window.parent.$("#tabs").tabs('close', title);
            parent.addTabs(title, '../Crm/Modules/AddPay.aspx?OrderId=' + $('#ID').val() + '&flag=2&entity=CrmPay&title=' + encodeURI(title) + '');
            RefreshDataParent();
            Close();
        } else {
            alert(str);
        }
    } catch (e) {
    }
    finally {
    }
}
var responseFailure = function (error) {
    alert("数据错误：" + error.statusText);
}
var callback = {
    success: responseSuccess,
    failure: responseFailure
};
var callback1 = {
    success: responseSuccess1,
    failure: responseFailure
};
//保存并转缴款单
var handlePay = function (obj) {
    if (flag == "0") {
        Save(1);
    } else if (flag == "1") {
        Save(2);
    } else if (flag == "2") {
        Save(3);
    }
}

//流程审核(同意)
var btnAgreeState = 0;
var handleAgree = function () {
    if (btnAgreeState == 0) {
        btnAgreeState = 1;
        var SaveUrl = Url + "?action=check&entity=CrmCustomerOrderAgree&OperatorInstanceId=" + OperatorInstanceId + "&WorkTaskInsId=" + WorkTaskInsId + "";
        if (Descript == "hsy") {
            SaveUrl = Url + "?action=check&entity=CrmCustomerOrderAgrees&OperatorInstanceId=" + OperatorInstanceId + "&WorkTaskInsId=" + WorkTaskInsId + "&WorkFlowInsId=" + WorkflowInsId + "";
        }
        YAHOO.util.Connect.asyncRequest('POST', SaveUrl, {
            success: function (res) {
                try {
                    var str = res.responseText;
                    if (str == "1") {
                        window.location.href = "../../Crm/BasePages/tooltip.aspx?worktaskInstanceId=" + WorkTaskInsId;
                    } else if (str == "2") {
                        alert("更新订单状态失败!流程提交不成功!");
                        return;
                    } else {
                        alert(str + "\n" + "操作异常!");
                        return;
                    }
                }
                catch (e) {
                }
                finally {
                }
            },
            failure: function (error) {
                alert("数据错误：" + error.statusText);
            }
        }, null);
    }
}
//不同意
var handleUnAgree = function () {
    if (btnAgreeState == 0) {
        btnAgreeState = 1;
        var vMessage = $("#txtReturn").val();
        if (confirm("您确定退回?")) {
            var SaveUrl = "../../Extend/AjaxData/CustomOperating.aspx?r=" + Math.random() + "&action=check&entity=CrmCustomerOrderUnAgree&msg=" + encodeURI(vMessage) + "" +
            "&OperatorInstanceId=" + OperatorInstanceId + "&WorkflowId=" + WorkFlowId + "&WorktaskId=" + WorkTaskId + "&WorkflowInsId=" + WorkflowInsId + "&WorktaskInsId=" + WorkTaskInsId + "";
            YAHOO.util.Connect.asyncRequest('POST', SaveUrl, {
                success: function (res) {
                    try {
                        var str = res.responseText;
                        if (str == "1") {
                            YAHOO.example.container.dialog4.hide();
                            window.location.href = "../../Crm/BasePages/tooltip.aspx?worktaskInstanceId=" + WorkTaskInsId;
                        } else {
                            alert(str + "\n" + "操作异常!");
                            return;
                        }
                    } catch (e) {
                    }
                    finally {
                    }
                },
                failure: function (error) {
                    alert("数据错误：" + error.statusText);
                }
            }, null);
        } else {
            btnAgreeState = 0;
        }
    }
}
//知道
var handleOK = function () {
    if (btnAgreeState == 0) {
        btnAgreeState = 1;
        var SaveUrl = Url + "?action=check&entity=CrmCustomerOrderOK&OperatorInstanceId=" + OperatorInstanceId + "&WorkTaskInsId=" + WorkTaskInsId + "";
        YAHOO.util.Connect.asyncRequest('POST', SaveUrl, {
            success: function (res) {
                try {
                    var str = res.responseText;
                    if (str == "1") {
                        window.location.href = "../../Crm/BasePages/tooltip.aspx?worktaskInstanceId=" + WorkTaskInsId;
                    } else {
                        alert("操作异常!");
                        return;
                    }
                }
                catch (e) {
                }
                finally {
                }
            },
            failure: function (error) {
                alert("数据错误：" + error.statusText);
            }
        }, null);
    }
}